<template>
  <!-- 安东呼叫类型表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    style="min-width: 600px; max-width: 800px"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="12"
          ><el-form-item label="工厂" prop="plantId" required>
            <el-select
              v-if="!props.isReadonly"
              @change="plantChange"
              v-model="formData.plantId"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in plants"
                :key="item.id"
                :label="item.organizationCode"
                :value="item.id"
              />
            </el-select>
            <span v-else> {{ formData.plantCode }}</span>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="报检类型编码" prop="inspectionTypeId" required>-->
        <!--            <el-select-->
        <!--              v-if="!props.isReadonly"-->
        <!--              @change="inspectionChange"-->
        <!--              v-model="formData.inspectionTypeId"-->
        <!--              placeholder="请选择"-->
        <!--            >-->
        <!--              <el-option-->
        <!--                v-for="item in inspections"-->
        <!--                :key="item.id"-->
        <!--                :label="item.inspectionTypeCode"-->
        <!--                :value="item.id"-->
        <!--              />-->
        <!--            </el-select>-->
        <!--            <span v-else>{{ formData.inspectionTypeCode }}</span>-->
        <!--          </el-form-item></el-col-->
        <!--        >-->
        <el-col :span="12">
          <el-form-item label="呼叫类型编码" prop="callTypeCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.callTypeCode"
              placeholder="请输入呼叫类型编码"
              clearable
              style="width: 200px"
            />

            <span v-else>{{ formData.callTypeCode }}</span>
          </el-form-item></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="呼叫类型名称" prop="callTypeName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.callTypeName"
              placeholder="请输入呼叫类型名称"
              clearable
              style="width: 200px"
            />

            <span v-else>{{ formData.callTypeName }}</span>
          </el-form-item></el-col
        >
        <el-col :span="12"
          ><el-form-item label="是否停机" prop="isStop">
            <template v-if="!props.isReadonly">
              <el-radio-group v-model="formData.isStop">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </template>
            <span v-else>{{
              dictionaryStore.filterDictName("YesNo", formData.isStop)
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12"
          ><el-form-item label="是否启用" prop="enabled">
            <template v-if="!props.isReadonly">
              <el-radio-group v-model="formData.enabled">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </template>
            <span v-else>{{
              dictionaryStore.filterDictName("YesNo", formData.enabled)
            }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            v-if="props.isReadonly !== false"
            label="创建时间"
            prop="createTime"
          >
            <span>{{ formData.createTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            v-if="props.isReadonly !== false"
            label="创建人"
            prop="createdUserName"
          >
            <span>{{ formData.createdUserName }}</span>
          </el-form-item></el-col
        >
      </el-row>
      <el-row>
        <el-col :span="12"
          ><el-form-item
            v-if="props.isReadonly !== false"
            label="修改时间"
            prop="lastUpdateTime"
          >
            <span>{{ formData.lastUpdateTime }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12"
          ><el-form-item
            v-if="props.isReadonly !== false"
            label="修改人"
            prop="lastUpdatedUserName"
          >
            <span>{{ formData.lastUpdatedUserName }}</span>
          </el-form-item></el-col
        >
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "ANDONANDCALLTYPEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
let plants = ref([]);
let inspections = ref([]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    getTypes(JSON.parse(JSON.stringify(props.data)).plantId);
    if (newVal === true) {
      setTimeout(() => {
        formRef.value.clearValidate();
      }, 50);
    }
  }
);

const rules = reactive({
  plantId: [{ required: true, message: "请选择工厂", trigger: "change" }],
  inspectionTypeId: [
    { required: true, message: "请选择报检类型", trigger: "change" },
  ],
  callTypeCode: [
    { required: true, message: "请输入呼叫类型编码", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  callTypeName: [
    { required: true, message: "请输入呼叫类型名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  autoInspection: [],
  inspectionTypeCode: [
    { required: true, message: "请选择报检类型编码", trigger: "change" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  enabled: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  callTypeCode: "",
  callTypeName: "",
  autoInspection: 1,
  inspectionTypeId: "",
  inspectionTypeCode: "",
  version: "",
  isStop: 1,
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        callTypeCode,
        callTypeName,
        autoInspection,
        inspectionTypeId,
        inspectionTypeCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        isStop,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        callTypeCode,
        callTypeName,
        autoInspection,
        inspectionTypeId,
        inspectionTypeCode,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        isStop,
        deleted,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.callTypeCode = "";
  formData.callTypeName = "";
  formData.autoInspection = 1;
  formData.inspectionTypeId = "";
  formData.inspectionTypeCode = "";
  formData.version = "";
  formData.isStop = 1;
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
}
onMounted(() => {
  getPlants();
});
const loading = ref(false);
async function getPlants() {
  const data = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data.data;
}
//获取报检类型
async function getTypes(id: string) {
  const data = await request({
    url: "/andon/andinspectiontype/getList",
    method: "post",
    data: {
      plantId: id,
    },
  });
  inspections.value = data.data;
}
function plantChange() {
  var plant = plants.value.find((item) => {
    return item.id === formData.plantId;
  });
  formData.plantCode = plant.organizationCode;
  formData.inspectionTypeId = "";
  formData.inspectionTypeCode = "";
  getTypes(formData.plantId);
}
function inspectionChange() {
  var inspection = inspections.value.find((item) => {
    return item.id === formData.inspectionTypeId;
  });
  formData.inspectionTypeCode = inspection.inspectionTypeCode;
}
/** 安东呼叫类型保存提交 */
function handleSubmit() {
  console.log(formData.plantId);
  console.log(formData.plantCode);

  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/andon/andcalltype/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
